<?php

/**
 * Capital Direct Lending (http://www.philbsd.com/cdl)
 *
 * Copyright (C) 2008 Philippine Business Solution Developers <http://www.philbsd.com>
 * All rights reserved.
 *
 *
 * LICENSE
 *
 * This source file is subject to the GNU General Public License v3 license
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@philbsd.com so we can send you a copy immediately.
 *
 * @copyright  (c) 2008 Philippine Business Solution Developers. (http://www.philbsd.com)
 * @license    http://www.gnu.org/licenses/gpl-3.0.txt
 * @version    $Id: UserController.php 38 2008-03-09 08:26:00Z philbsd $
 */

class UserController extends Philbsd_Controller_Action
{
    protected $_session;

	protected $_userTable;

	protected $_userProfileTable;

	protected $_roleTable;

    public function init()
    {
        $this->_session = new Zend_Session_Namespace(__CLASS__);
		$this->_userTable = new Philbsd_Model_Users();
		$this->_userProfileTable = new Philbsd_Model_User_Profiles();
		$this->_roleTable = new Philbsd_Model_Roles();
    }

    public function indexAction()
    {
		$users = array();
		$userProfileRowSet = $this->_userProfileTable->fetchAll();
		while ($userProfileRow = $userProfileRowSet->current()) {
			$user = $userProfileRow->toArray();
			$roleRow = $userProfileRow->findParentRow('Philbsd_Model_Roles');
			$user['role'] = $roleRow->name;
			$users[] = $user;
			$userProfileRowSet->next();
		}
		$this->view->records = $users;

		if (isset($this->_session->message)) {
			$this->view->message = $this->_session->message;
			unset($this->_session->message);
		}

		$this->render();
    }

	function viewAction()
	{
		$params = $this->getRequest()->getUserParams();
		if (!isset($params['id'])) {
			$this->_redirect('admin/user');
		}
		$userProfileRowSet = $this->_userProfileTable->find($params['id']);
		$userProfileRow = $userProfileRowSet->current();
		$user = $userProfileRow->toArray();
		$roleRow = $userProfileRow->findParentRow('Philbsd_Model_Roles');
		$user['role'] = $roleRow->name;

		$this->view->record = $user;
		$this->render();
	}

	public function addAction()
	{
		if (isset($_POST['btnCancel'])) {
			$this->_redirect('admin/user');
		}
		$userProfileRow = $this->_userProfileTable->createRow();

		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			$messages = array();

			$input = $this->_validateInputs();
			if (!$input->isValid()) {
				$messages = $input->getMessages();
			}
			$username = strtolower(trim($_POST['username']));
			if (strlen($username) == 0) {
				$messages[] = array('username'=>"Username must not be empty");
			} else {
				if ($userProfileRow = $this->_userProfileTable->fetchRow("username = '{$username}'")) {
					$messages[] = array('username'=>"Username already exists.");
				}
			}

			if (!$messages) {
				$userProfileRow->username = $username;
				$userProfileRow->role_id = $_POST['role_id'];
				$userProfileRow->last_name = $input->getUnescaped('last_name');
				$userProfileRow->first_name = $input->getUnescaped('first_name');
				$userProfileRow->middle_name = $input->getUnescaped('middle_name');
				$userProfileRow->website = $input->getUnescaped('website');
				$userProfileRow->email = $input->getUnescaped('email');
				$userProfileRow->phone = $input->getUnescaped('phone');
				$userProfileRow->mobile = $input->getUnescaped('mobile');
				$userProfileRow->address = $input->getUnescaped('address');

				if ($id = $userProfileRow->save()) {
					$this->_session->message = "User profile Id#{$id} added successfully";
					$this->_redirect('admin/user');
				} else {
					$messages[] = array('add'=>"Failed to add user profile.");
				}

	            $this->_redirect('admin/user');
			}
			$this->view->messages = $messages;
		}

		$this->view->roles = $this->_getRoles();
		$this->render();
	}

	public function editAction()
    {
		if (isset($_POST['btnCancel'])) {
			$this->_redirect('admin/user');
		}
		$params = $this->getRequest()->getUserParams();

		if (!isset($params['id'])) {
			$this->_redirect('admin/user');
		}

		$userProfileRowSet = $this->_userProfileTable->find($params['id']);
		if (!($userProfileRow = $userProfileRowSet->current())) {
			$this->_redirect('admin/user');
		}

		$this->view->record = $userProfileRow->toArray();
		$this->view->roles = $this->_getRoles();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			$messages = array();

			$input = $this->_validateInputs();
			if (!$input->isValid()) {
				$messages = $input->getMessages();
			}

			if (!$messages) {
				$userProfileRow->role_id = $_POST['role_id'];
				$userProfileRow->last_name = $input->getUnescaped('last_name');
				$userProfileRow->first_name = $input->getUnescaped('first_name');
				$userProfileRow->middle_name = $input->getUnescaped('middle_name');
				$userProfileRow->website = $input->getUnescaped('website');
				$userProfileRow->email = $input->getUnescaped('email');
				$userProfileRow->phone = $input->getUnescaped('phone');
				$userProfileRow->mobile = $input->getUnescaped('mobile');
				$userProfileRow->address = $input->getUnescaped('address');

				if ($userProfileRow->save() == $params['id']) {
					$this->_session->message = "User profile Id#{$userProfileRow->id} updated successfully";
					$this->_redirect('admin/user');
				} else {
					$messages[] = "Failed to update user profile.";
				}
			}
			$this->view->messages = $messages;
        }

        $this->render();
    }

	function deleteAction()
	{
		if (isset($_POST['btnCancel'])) {
			$this->_redirect('admin/user');
		}
		$params = $this->getRequest()->getUserParams();

		if (!isset($params['id'])) {
			$this->_redirect('admin/user');
		}
		$userProfileRowSet = $this->_userProfileTable->find($params['id']);
		$userProfileRow = $userProfileRowSet->current();

		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
			$userProfileRow->delete();
			$this->_session->message = "User profile Id#{$params['id']} deleted successfully";
            $this->_redirect('admin/user');
		}

		$user = $userProfileRow->toArray();
		$roleRow = $userProfileRow->findParentRow('Philbsd_Model_Roles');
		$user['role'] = $roleRow->name;

		$this->view->record = $user;
		$this->render();
	}

	protected function _getRoles()
	{
		$roles = array();
		$roleRowSet = $this->_roleTable->fetchAll();
		if ($roleRow = $roleRowSet->current()) {
			$roleRowSet->next();
			while ($roleRow = $roleRowSet->current()) {
				$roles[] = $roleRow->toArray();
				$roleRowSet->next();
			}
		}
		return $roles;
	}

	protected function _validateInputs()
	{
		$filters = array(
			'last_name' => 'StringTrim',
			'first_name' => 'StringTrim',
			'middle_name' => 'StringTrim',
			'website' => 'StringTrim',
			'email' => 'StringTrim',
			'phone' => 'StringTrim',
			'mobile' => 'StringTrim',
			'address' => 'StringTrim',
			);

		$validators = array(
			'last_name' => array(
				array('StringLength', 3, 32),
				'messages' => array(
					'Last name must be between %min% and %max% characters in length'
					)
				),
			'first_name' => array(
				array('StringLength', 3, 32),
				'messages' => array(
					'First name must be between %min% and %max% characters in length'
					)
				),
			'middle_name' => array(
				array('StringLength', 3, 32),
				'messages' => array(
					'Middle name must be between %min% and %max% characters in length'
					)
				),
			'website' => array(
				'allowEmpty' => true,
				array('StringLength', 5),
				'messages' => array(
					0 => 'Website, if provided, must be at least %min% characters in length'
					)
				),
			'email' => array(
				array('StringLength', 3, 32),
				'messages' => array(
					'Email must be between %min% and %max% characters in length'
					)
				),
			'phone' => array(
				'allowEmpty' => true,
				array('StringLength', 7),
				'messages' => array(
					0 => 'Phone, if provided, must be at least %min% characters in length'
					)
				),
			'mobile' => array(
				'allowEmpty' => true,
				array('StringLength', 7),
				'messages' => array(
					0 => 'Phone, if provided, must be at least %min% characters in length'
					)
				),
			'address' => array(
				'allowEmpty' => true,
				array('StringLength', 5),
				'messages' => array(
					0 => 'Phone, if provided, must be at least %min% characters in length'
					)
				),
			);

		$input = new Zend_Filter_Input($filters, $validators, $_POST);

		return $input;
	}
}
